<!--
 * @Author: zhoulei0232
 * @Date: 2022-12-08 00:37:02
 * @LastEditTime: 2023-01-11 21:23:10
 * @LastEditors: zhoulei0232
 * @Description: 
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
      <el-form-item label="用户QQ号:" prop="queryUserName">
        <el-input v-model="queryParams.queryUserName" placeholder="根据QQ号模糊搜索" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="昵称:" prop="queryNickname">
        <el-input v-model="queryParams.queryNickname" placeholder="根据昵称模糊搜索" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态:" prop="queryStatus">
        <el-select v-model="queryParams.queryStatus" clearable placeholder="请选择">
          <el-option v-for="item in stutasList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户类型" prop="queryType">
        <el-select v-model="queryParams.queryType" clearable placeholder="请选择">
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="queryRemarks">
          <el-input v-model="queryParams.queryRemarks" placeholder="根据备注模糊搜索" clearable style="width: 240px"
            @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>

        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Upload" @click="handleUpload">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="painterList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">

      <el-table-column label="序号" align="center" type="index" width="100" />

      <el-table-column label="用户QQ号" align="left" prop="id" :show-overflow-tooltip="true" sortable />

      <el-table-column label="昵称" align="center" prop="nickname" />
     

      <el-table-column label="店铺昵称" align="center" prop="alias_nickname"  >
         <template #default="scope">
          {{ scope.row.alias_nickname||'-' }}
        </template>
      </el-table-column>

      <el-table-column label="用户类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="typeList" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增或修改数据 -->
    <el-dialog :title="title" v-model="open" width="480px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="22">
            <el-form-item label="用户QQ号" prop="id">
              <el-input v-model="form.id" :disabled="title !== '新增'" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入" />
            </el-form-item>
          </el-col>
         <el-col :span="22">
            <el-form-item label="店铺昵称" prop="alias_nickname">
              <el-input v-model="form.alias_nickname" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="用户类型" prop="type">
              <el-select v-model="form.type" clearable placeholder="请选择">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" :rows="2" placeholder="请输入备注" v-model="form.remarks">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 导入功能 -->
    <el-dialog :title="title" v-model="dialogOpen2" width="780px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-form-item label="模板下载">
            <el-button type="primary" @click="submitUploadFileDemo">下载xlsx模板</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件上传">
            <el-upload class="upload-demo" :action="uploadUrl" :file-list="fileList" :before-upload="beforeFileUpload"
              :on-success="onSuccessFile">
              <el-button type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请按模板规范上传</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel2">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导出 按钮 -->
    <el-dialog :title="title" v-model="dialogOpen1" width="780px" append-to-body>
      <el-form ref="orderRef1" :model="dialogForm1" label-width="120px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="用户类型" prop="type">
              <el-select v-model="dialogForm1.type" clearable placeholder="请选择">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            备注：选择对应的用户类型，如果不选则导出全部用户。
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitExport" :loading="loadingBtn">确 定</el-button>
          <el-button @click="dialogCancel1">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="User">
import {
  listUser,
  updateUser,
  addUser,
  downExcelFile,
  downExcelUser
} from "@/api/business/user";

import { userTypeEnums, stutasEnums } from "@/utils/enums"
import { useDebounceFn } from "@vueuse/core";

const { proxy } = getCurrentInstance();


// 文件上传地址

const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFileUser/file";

const painterList = ref([]);
const dialogOpen1 = ref(false); // 导出表格

const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const open = ref(false); // 修改用户弹框
const dialogOpen2 = ref(false); // 导入表格
const fileList = ref([]);
const loadingBtn = ref(false);


const data = reactive({
  typeList: userTypeEnums,
  stutasList: stutasEnums,
  form: {},

  dialogForm1: {
    type: undefined,

  }, // 导出弹出框选择
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryUserName: '',
    queryNickname: '',
    queryRemarks: '',
    queryStatus: '',
    queryType: '',
    orderName: "",
    orderType: "DESC",
  },
  rules: {
    id: [{ required: true, message: "用户qq不能为空", trigger: "blur" }],
    password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules,
  typeList,
  dialogForm1,
  stutasList 
  } =
  toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then((response) => {
    painterList.value = response.data.rows;
    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
 
}
/** 表单重置 */
function reset() {
  form.value = {
 
    password: 123, // 默认密码123
  };
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.noticeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  form.value = {
    type: 1,
    status: 1
  }
  title.value = "新增";
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = {...row};
  open.value = true;
  title.value = "修改";
}

/**启用 启用停用 */
function handleStatusChange(row) {
  let text = row.status ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.id + '"用户吗?')
    .then(function () {
      let sendData = {
        ...row,
        id: row.id,
        status: row.status,
      };
      return updateUser(sendData);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status == 1 ? 2 : 1;
    });
}

function handleSortChange(column, prop, order) {
  if (order == "descending") {
    data.queryParams.orderName = prop;
    data.queryParams.orderType = "DESC";
  } else if (order == "ascending") {
    data.queryParams.orderName = prop;
    data.queryParams.orderType = "ASC";
  } else {
    data.queryParams.orderName = "updatedAt";
    data.queryParams.orderType = "DESC";
  }
}
// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);
/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (title.value != '新增') {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 表单重置 */
function dialogReset1() {
  proxy.resetForm("orderRef1");
}
function handleExport() {
  dialogReset1();
  dialogOpen1.value = true;
  title.value = "导出表格";
}
/** 导入表格 */
function handleUpload() {
  dialogReset2();
  dialogOpen2.value = true;
  title.value = "导入表格";
}
/** 表单重置 */
function dialogReset2() {
  fileList.value = [];
}
/** 取消按钮 */
function dialogCancel1() {
  dialogOpen1.value = false;
  dialogReset1();
}
/** 取消按钮 */
function dialogCancel2() {
  dialogOpen2.value = false;
  dialogReset2();
}
/** 下载标准模板 */
function submitUploadFileDemo(response) {
  let fileName = "用户批量上传标准模板2025.xlsx";
  loadingBtn.value = true;
  downExcelFile().then((response) => {
    loadingBtn.value = false;
    downFile(response, fileName);
  });
}
// 附件
const beforeFileUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    proxy.$modal.msgError("文件大于 2MB!");
    return false;
  }
  return true;
};
// 批量提交成功后
function onSuccessFile(response) {
  if (response.code == 200) {
    proxy.$modal.msgSuccess(response.msg);
  } else {
    proxy.$modal.msgError(response.msg);
  }
  getList();
}

// 可以将此方法封装
function downFile(content, filename) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink);
  // 触发点击
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
  proxy.$modal.msgSuccess("操作成功");
}
/** 导出 */
function submitExport() {
  const dataForm = dialogForm1.value;
  let fileName = "用户列表" + ".xlsx";
  loadingBtn.value = true;
  downExcelUser(dataForm).then((response) => {
    loadingBtn.value = false;

    downFile(response, fileName);
  });
}


getList();

</script>
